﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.IO;

namespace TEAA
{
    public class XmlSchemaValidator
    {

        /// <summary>
        /// Show if XML is valid
        /// </summary>
        private bool isValidXml;

        /// <summary>
        /// Error message on validation fail
        /// </summary>
        private string validationError = "";

        /// <summary>
        /// SchemaSet  containing the schema to use for validation
        /// </summary>
        private XmlSchemaSet schemaSet;

        public String ValidationError
        {
            get
            {
                return this.validationError;
            }
        }

        public bool IsValidXml
        {
            get
            {
                return this.isValidXml;
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="schemaNamespace">Namespace of the schema</param>
        /// <param name="schemaUri">URI of the schema</param>
        public XmlSchemaValidator(string schemaNamespace, string schemaUri)
        {
            schemaSet = new XmlSchemaSet();
            schemaSet.Add(schemaNamespace, schemaUri);
        }

        /// <summary>
        /// ValidationEventHandler method called on validation error
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ValidationCallBack(object sender, ValidationEventArgs args)
        {
            isValidXml = false;
            validationError = args.Message;
        }

        /// <summary>
        /// Validate an XDocument against the XML schema
        /// </summary>
        /// <param name="document">XDocument</param>
        public void ValidateXDocument(XDocument document)
        {
            isValidXml = true;
            validationError = "";
            document.Validate(schemaSet, new ValidationEventHandler(ValidationCallBack));
        }

    }
}
